import sys
##
##
import socket
import threading
from common import utils
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.Ui_my_main_window import Ui_MainWindow
class MainWindow(QMainWindow):
    #a.定义信号
    #参数1：0需要更新数据，1收到新的消息
    #参数2：数据
    msg_recv_signal = pyqtSignal(int,object)#信号
    
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.tcp_client: socket.socket = None
        
        #c.将信号连接到槽
        self.msg_recv_signal.connect(self.on_data_recv_slot)
        
        #加载Ui内容
        self.ui.setupUi(self)
        self.init_ui()
        
    #更新ui的连接状态
    def update_connect_state(self):
        if self.tcp_client is None:
            #连接网络
            self.ui.btn_connect.setText("连接网络")
            self.ui.btn_connect.setIcon(QIcon(":ic/连接 (2).png"))
        else:
            #断开连接
            self.ui.btn_connect.setText("断开连接")
            self.ui.btn_connect.setIcon(QIcon(":ic/连接 (1).png"))
            
    #更新ui图标信息和槽函数        
    @pyqtSlot(int,object)
    def on_data_recv_slot(self,type_t,msg):
        if type_t == 0:
            self.update_connect_state()
        elif type_t == 1:     
            thread_name = threading.current_thread().name
            print(msg, " thread->", thread_name)   
            self.ui.edit_recv.appendPlainText(msg)
            
    #客户端运行函数    
    def run_tcp_client(self, target_ip, target_port):
        #创建socket对象
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #连接服务器
        try:
            self.tcp_client.connect((target_ip, int(target_port)))
        except Exception as e:
            print("服务器连接失败", e)#连接服务器异常
            self.tcp_client = None
            return
        self.msg_recv_signal.emit(0,None)#gui更新连接状态
        
        local_ip, local_port = self.tcp_client.getsockname()
        print("服务器连接成功,本机信息ip:{} port:{}".format(local_ip, local_port))
        
        
        try:
            while True:
                #阻塞接收信息
                bytes_data = self.tcp_client.recv(1024)
                if bytes_data:
                    msg = utils.decode_data(bytes_data)#收到的信息显示到界面对话框中
                    print("收到数据：",msg)
                    # self.on_data_recv_slot(msg)
                    #通过信号和槽机制，将消息发到主线程执行
                    self.msg_recv_signal.emit(1,msg)
                    
                else:
                    print("服务器已断开！")#空字符串
                    break
        except:
            print("已断开连接！")
        if self.tcp_client is not None:
            self.tcp_client.close()
            self.tcp_client = None
            
        self.msg_recv_signal.emit(0,None)#gui更新连接状态
    
    #点击连接按钮    
    @pyqtSlot()    
    def on_btn_connect_clicked(self):#连接
        #再次点击，断开连接
        if self.tcp_client is not None:
            self.tcp_client.close()
            self.tcp_client = None
            return 
           
        #获取用户输入的ip和端口
        mode = self.ui.cb_mode.currentText()
        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        print(f"连接{mode} {target_ip}:{target_port}")
        t1 = threading.Thread(target=self.run_tcp_client, args=(target_ip, target_port),daemon=True)
        t1.start()
    
    #点击发送按钮    
    @pyqtSlot()   
    def on_btn_send_clicked(self):#发送
        text = self.ui.edit_send.toPlainText()
        if len(text) == 0:
            self.statusBar().showMessage("请先输入要发送的消息！")
            return
        if self.tcp_client is None:
            self.statusBar().showMessage("请先连接服务器！")
            QMessageBox.warning(self, "警告", "请先连接服务器！", QMessageBox.Yes)
            return
        self.tcp_client.send(text.encode())
        
    #初始化ui 
    def init_ui(self):
        #初始化target_ip和target_port
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8080")
        # self.ui.btn_connect.clicked.connect(self.on_btn_connect_clicked)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywindow = MainWindow()
    mywindow.show()
    sys.exit(app.exec_())